<template>
  <!-- 当点击 取消按钮 时，关闭弹窗 -->
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="60%"
    top="4vh"
    :append-to-body="true"
    @close="clearDialog()"
    v-loading="loading"
    :close-on-click-modal="false"
  >
    <ele-form v-model="dialogfrom" v-bind="formConfig" ref="form"> </ele-form>
    <barcode-print
      :barcodeInfo="barcodeInfo"
      ref="print"
      :key="time"
      :isPrint="false"
      v-if="Object.keys(barcodeInfo).length > 0"
    ></barcode-print>
    <div slot="footer" class="dialog-footer">
      <el-button @click="clearDialog()">{{ $t("common.cancel") }}</el-button>
      <el-button type="primary" @click="handleShow">{{
        $t("printBoxCode.previewAndPrint")
      }}</el-button>
    </div>
    <el-dialog
      width="20%"
      :title="$t('capacityCode.printFilter')"
      :visible.sync="innerVisible"
      :append-to-body="true"
      @close="clearFormDialog()"
      v-loading="loading"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules">
        <el-form-item
          :label="$t('capacityCode.printQuantity')"
          label-width="85px"
          prop="amount"
        >
          <el-input-number
            size="small"
            v-model="form.amount"
            :step="1"
            :min="1"
            :max="Number(maxnum)"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item :label="$t('mesProdOtherCode.printingTimes')" label-width="85px">
          <el-input-number size="small" disabled v-model="form.printingTimes"></el-input-number>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearFormDialog()">{{
          $t("common.cancel")
        }}</el-button>
        <el-button type="primary" @click="handleRequest">{{
          $t("common.submit")
        }}</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  getBarcodePrintTempList,
  checkOtherCode,
  printTemplateInfo,
  splitPrintList,
  getCodeCount,
  selectCommonProduceRelByProduce,
  getPrintingTimes,
} from "@/api/print/mesProdOthercode";
import { getDict } from "@/api/common";
import BarcodePrint from "@/components/barcodePrint/barcodePrint";

let arrBarcodePrintingList2 = [];
export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
        this.barcodeInfo = {};
      }
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { BarcodePrint },
  data() {
    let that = this;
    return {
      loading: false,
      time: 0,
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            type: "input",
            label: $i18n.t("mesOtherCodePrinting.orderCode"),
            layout: 8,
            required: true,
            disabled: true,
          },
          prodCode: {
            type: "input",
            label: $i18n.t("mesOtherCodePrinting.prodCode"),
            layout: 8,
            required: true,
            disabled: true,
          },
          prodName: {
            type: "input",
            label: $i18n.t("mesOtherCodePrinting.prodName"),
            layout: 8,
            required: true,
            disabled: true,
          },
          quantity: {
            type: "number",
            label: $i18n.t("mesOtherCodePrinting.planQuantity"),
            layout: 8,
            required: true,
            disabled: true,
          },
          codeType: {
            type: "select",
            label: $i18n.t("mesOtherCodePrinting.codeType"),
            layout: 8,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getDict("mes_code_type");
              return list.data.result;
            },
            on: {
              change: async (val) => {
                const params = {
                  orderCode: that.dialogfrom.orderCode,
                  codeType: val,
                  row: that.dialogfrom,
                };
                that.getCodeCount(params);
              },
            },
            required: true,
            disabled: false,
          },
          printQuantity: {
            type: "number",
            label: $i18n.t("mesOtherCodePrinting.printQuantity"),
            layout: 8,
            required: true,
            disabled: true,
          },
          quantityPrinted: {
            type: "number",
            label: $i18n.t("mesOtherCodePrinting.quantityPrinted"),
            layout: 8,
            required: true,
            disabled: true,
          },
          quantityNotPrinted: {
            type: "number",
            label: $i18n.t("mesOtherCodePrinting.quantityNotPrinted"),
            layout: 8,
            required: true,
            disabled: true,
          },
          barcodePrintTemp: {
            type: "select",
            label: $i18n.t("mesOtherCodePrinting.barcodePrintTemp"),
            layout: 8,
            disabled: (data) => {
              return data.quantityPrinted || data.quantityPrinted === 0
                ? true
                : false;
            },
            prop: {
              value: "templateName",
              text: "templateName",
            },
            options: async (data) => {
              if (!data.codeType) return;
              const params = {
                goodsCode: data.prodCode,
                templateType: data.codeType,
                type: "template",
              };
              console.log(params);
              const list = await selectCommonProduceRelByProduce(params);
              return list.data.result;
            },
            required: true,
            on: {
              change: (data, e) => {
                that.handleChange(data);
              },
            },
          },
        },
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      innerVisible: false,
      form: {
        amount: 0,
        printingTimes: 0,
      },
      rules: {
        amount: [
          {
            required: true,
            message: $i18n.t("mesOtherCodePrinting.printingQuantity"),
            trigger: "blur",
          },
        ],
      },
      maxnum: 9999,
      list: [],
    };
  },
  methods: {
    //初始化
    init(params) {
      params.barcodePrintTemp = "";
      console.log("params", params);
      this.dialogfrom = params;
      this.barcodeInfo = params;
      this.visible = true;
      this.$nextTick(() => {
        this.getBarcodePrintTempList();
        setTimeout(() => {
          this.handleChange(this.dialogfrom.barcodePrintTemp);
        }, 1000);
      });
    },

    /**
     * @author bing
     * @since 2022-11-18 14:47:33
     *  根据工单编码+分类获取其它码生码数量，已打印数量、未打印数量
     */
    async getCodeCount(params) {
      let barcodeInfo = this.barcodeInfo;
      console.log("123123:", params);
      let check = params.row;
      let checkOtherCodeData = await checkOtherCode(params);
      let checkOtherCodeValue = checkOtherCodeData.data.result;
      if (!checkOtherCodeValue) {
        this.$confirm(
          $i18n.t("mesOtherCodePrinting.isCreateBarcode"),
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
          }
        ).then(() => {
          this.$parent.showCreateNext(check);
          this.clearDialog();
        });
        return;
      }

      let res = await getCodeCount(params);
      let { quantity, quantityPrinted, quantityNotPrinted, barcodePrintTemp } =
        res.data.result;
      this.dialogfrom.printQuantity = quantity;
      this.dialogfrom.quantityPrinted = quantityPrinted;
      this.dialogfrom.quantityNotPrinted = quantityNotPrinted;
      if (quantityNotPrinted > 0 && !barcodePrintTemp) {
        this.formConfig.formDesc.barcodePrintTemp.disabled = false;
      }
      if (barcodePrintTemp) {
        this.dialogfrom.barcodePrintTemp = barcodePrintTemp;
        this.formConfig.formDesc.barcodePrintTemp.disabled = true;
      }
    },

    async getBarcodePrintTempList() {
      const res = await getBarcodePrintTempList();
      arrBarcodePrintingList2 = res.data.result;
    },

    // 条码模板选择
    handleChange(e) {
      if (arrBarcodePrintingList2.length == 0) return;
      if (!this.dialogfrom.barcodePrintTemp) return;

      let obj = arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName;
      });
      this.loading = true;
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime();
          this.barcodeInfo = { ...this.barcodeInfo, ...res.data.result };
        })
        .finally((res) => {
          this.loading = false;
        });
    },

    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
    },
    clearFormDialog() {
      this.innerVisible = false;
      this.form.amount = 0;
      this.maxnum = 9999;
    },
    async handleShow() {
      if (!this.dialogfrom.barcodePrintTemp) {
        this.$message.warning(
          this.$i18n.t("mesOtherCodePrinting.barcodePrintTempCheckMsg")
        );
        return;
      }
      if (this.dialogfrom.printQuantity === 0) {
        this.$message.warning(this.$i18n.t("mesOtherCodePrinting.canNotPrint"));
        return;
      }
      if (this.dialogfrom.quantityNotPrinted === 0) {
        this.$message.warning(this.$i18n.t("mesOtherCodePrinting.alreadyPrint"));
        return;
      }
      // ---------获取打印次数-----------------
      // let res = await getPrintingTimes({ goodsCode: this.dialogfrom.prodCode });
      // if (res.data.result && res.data.result.frequency)
      //   this.form.printingTimes = res.data.result.frequency;
      // ------------------------------------
      this.innerVisible = true;
      this.maxnum = this.dialogfrom.quantityNotPrinted;
      this.form.amount = this.dialogfrom.quantityNotPrinted;
    },
    // 点击打印按钮
    handleRequest() {
      if (this.form.amount <= 0) {
        this.$message.warning($i18n.t("mesOtherCodePrinting.amountCheckMsg"));
        return;
      }
      // if (this.form.printingTimes == 0) {
      //   this.$message.warning($i18n.t("printBoxCode.unableToPrint"));
      //   return;
      // }
      this.$refs.form.handleSubmitForm();
      this.$refs.form.validate().then((valid) => {
        let data = {
          isPrint: 0,
          orderCode: this.dialogfrom.orderCode, //'生产工单号',
          amount: this.form.amount,
          barcodePrintTemp: this.dialogfrom.barcodePrintTemp,
          codeType: this.dialogfrom.codeType,
        };
        splitPrintList(data).then((res) => {
          if (res.data.success) {
            let list = res.data.result,
              info = this.barcodeInfo,
              infoList = [];
            if (Array.isArray(list) && list.length > 0) {
              list.forEach((item) => {
                infoList.push(item);
              });
            }
            delete info.values;
            // ----条码打印多份（条码数量根据打印次数printingTimes重新计算）----
            let newInfoList = [];
            infoList.forEach((v) => {
              newInfoList = [...newInfoList, v];
            });
            info.values = newInfoList;
            localStorage.splitPrint = JSON.stringify(info);
            this.clearFormDialog();
            this.clearDialog();
            window.open("/mom/component/mes/splitPrint?type=9");
          }
        });
      });
    },
  },
};
</script>
